package cn.upfinder.datalibrary.Api;

import android.content.Context;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import cn.upfinder.datalibrary.Bean.GankData;
import cn.upfinder.datalibrary.Bean.VideoEntity;
import cn.upfinder.datalibrary.Config.VideoType;
import cn.upfinder.datalibrary.Utils.ParseHtmlUtil;
import okhttp3.ResponseBody;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by upfinder on 2016/10/28 0028.
 */
public class ApiManage {
    private static ApiManage apiManage;

    // Charset
    private final String TO_CHARSET_NAME = "utf-8";


    //优酷服务接口
    private YouKuApi youKuApi;

    //搜酷服务接口
    private SouKuApi souKuApi;


    private Object monitor = new Object();

    public ApiManage() {
    }

    /**
     * Gets instence.
     *
     * @return the instence
     */
    public static ApiManage getInstence() {
        if (apiManage == null) {
            synchronized (ApiManage.class) {
                if (apiManage == null) {
                    apiManage = new ApiManage();
                }
            }
        }
        return apiManage;
    }


    /*获取优酷服务
    * */
    private YouKuApi getYouKuService(Context context) {
        if (youKuApi == null) {
            synchronized (monitor) {
                if (youKuApi == null) {
                    youKuApi = RetrofitManage.getInstance().getYouKuRetrofit(context).create(YouKuApi.class);
                }
            }
        }
        return youKuApi;
    }

    private SouKuApi getSouKuService(Context context) {
        if (souKuApi == null) {
            synchronized (monitor) {
                if (souKuApi == null) {
                    souKuApi = RetrofitManage.getInstance().getSouKuRetrofit(context).create(SouKuApi.class);
                }
            }
        }
        return souKuApi;
    }


    /*获取优酷综艺*/
    public void getYoukuMovie(Context context, int page, Observer<ArrayList<VideoEntity>> observer) {
        Observable<ArrayList<VideoEntity>> observable = getYouKuService(context).getMovie(page).map(new Func1<ResponseBody, String>() {
            @Override
            public String call(ResponseBody responseBody) {
                try {
                    return new String(responseBody.bytes(), TO_CHARSET_NAME);
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }).map(new Func1<String, ArrayList<VideoEntity>>() {
            @Override
            public ArrayList<VideoEntity> call(String s) {
                Document document = Jsoup.parse(s);
                Elements elements = document.select("div.box-series").select("ul.panel");
                Elements movieItems = elements.select("div.p-thumb");
                ArrayList<VideoEntity> videoEntityArrayList = new ArrayList<VideoEntity>();
                for (Element item : movieItems) {
                    VideoEntity videoEntity = new VideoEntity();
                    Element element = item.select("a[href]").first();
                    String fullName = element.text();
                    videoEntity.setUrl("http:" + element.attr("href"));
                    videoEntity.setImgUrl(item.select("img").first().attr("src"));
                    videoEntity.setName(item.select("img").first().attr("alt"));
                    videoEntity.setVideotype(VideoType.YOUKU_MOVIE);
                    videoEntityArrayList.add(videoEntity);
                }

                return videoEntityArrayList;
            }
        });

        setSubscribe(observable, observer);
    }


    /*获取优酷综艺*/
    public void getYouKuPlay(Context context, int page, Observer<ArrayList<VideoEntity>> observer) {

        Observable<ArrayList<VideoEntity>> observable = getYouKuService(context).getPlay(page).map(ParseHtmlUtil.getStringFunc1()).map(ParseHtmlUtil.getYouKuVideoListFunc()).map(new Func1<ArrayList<VideoEntity>, ArrayList<VideoEntity>>() {
            @Override
            public ArrayList<VideoEntity> call(ArrayList<VideoEntity> videoEntities) {
                for (VideoEntity entity : videoEntities) {
                    entity.setVideotype(VideoType.YOUKU_PLAY);
                }
                return videoEntities;
            }
        });
        setSubscribe(observable, observer);

    }


    /*
    * 获取美女热舞视频列表
    * */
    public void getSouKuBeautyDanceList(Context context, int page, Observer<ArrayList<VideoEntity>> observer) {
        Observable<ArrayList<VideoEntity>> observable = getSouKuService(context).getBeautyDanceList(14, 10, "a2h0k.8191407.0.0", page).map(ParseHtmlUtil.getStringFunc1()).map(ParseHtmlUtil.getSouKuBeautyDanceFunc());
        setSubscribe(observable, observer);
    }


    /*
    * 插入观察者，设置监听
    * */
    private <T> void setSubscribe(Observable<T> observable, Observer<T> observer) {
        observable.subscribeOn(Schedulers.io())
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

}
